package com.fengye.security.jwt.process;

import com.pearadmin.common.tools.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理
 *
 * 请求 /jwt/login 时起作用,认证失败,返回失败的结果
 */
@Component("jwtAuthenticationFailureHandler")
@Slf4j
public class JwtAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        String msg = "登陆失败";
        if (exception instanceof PreAuthenticatedCredentialsNotFoundException) { // 用户名未空
            msg = "用户认证信息为空";
        } else if (exception instanceof UsernameNotFoundException) {
            msg = "账户名不存在!";
        }else if (exception instanceof BadCredentialsException) {
            msg = "密码输入错误!";
        } else if (exception instanceof LockedException) {
            msg = "账户被锁定，请联系管理员!";
        } else if (exception instanceof CredentialsExpiredException) {
            msg = "密码过期，请联系管理员!";
        } else if (exception instanceof AccountExpiredException) {
            msg = "账户过期，请联系管理员!";
        } else if (exception instanceof DisabledException) {
            msg = "账户被禁用，请联系管理员!";
        }else{
            msg = "未知错误类型";
            log.error("捕捉到未知错误",exception.getCause());
        }
        // 清空认证信息
        SecurityContextHolder.clearContext();

        // 401
        ServletUtil.write(msg, HttpStatus.UNAUTHORIZED);
    }


}
